package com.example.demo.service;

import com.example.demo.converter.ClothConverter;
import com.example.demo.converter.UserConverter;
import com.example.demo.dao.Cloth;
import com.example.demo.dao.ClothRepository;
import com.example.demo.dao.User;
import com.example.demo.dao.UserRepository;
import com.example.demo.dto.ClothDTO;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;
import java.util.Set;

@Service
public class ClothServiceImpl implements ClothService {

    @Autowired
    private ClothRepository clothRepository;

    @Autowired
    private ImageService imageService; // 注入 ImageService
    @Autowired
    private UserRepository userRepository;

    @Override
    public Set<ClothDTO> getClothByUserId(long userId) {
        try {
            Set<Cloth> clothes = clothRepository.findByUserId(userId);
            Set<ClothDTO> clothDTOs = ClothConverter.convertToClothDTOSet(clothes);

            // 添加图像字节到每个 ClothDTO
            for (ClothDTO clothDTO : clothDTOs) {
                String imageName = clothDTO.getImageName();
                if (imageName != null && !imageName.isEmpty()) {
                    byte[] imageBytes = imageService.getImageAsBytes(imageName);
                    clothDTO.setImageBytes(imageBytes);
                }
            }
            return clothDTOs;
        } catch (IOException e) {
            throw new ServiceException("Error retrieving image for Cloth", e);
        } catch (Exception e) {
            throw new ServiceException("Error converting Cloth to ClothDTO", e);
        }
    }

    @Override
    public Set<ClothDTO> getClothByUserIdAndCategory(long userId, String category) {
        try {
            Set<Cloth> clothes = clothRepository.findByUserIdAndCategory(userId, category);
            Set<ClothDTO> clothDTOs = ClothConverter.convertToClothDTOSet(clothes);

            // 添加图像字节到每个 ClothDTO
            for (ClothDTO clothDTO : clothDTOs) {
                String imageName = clothDTO.getImageName();
                if (imageName != null && !imageName.isEmpty()) {
                    byte[] imageBytes = imageService.getImageAsBytes(imageName);
                    clothDTO.setImageBytes(imageBytes);
                }
            }
            return clothDTOs;
        } catch (IOException e) {
            throw new ServiceException("Error retrieving image for Cloth", e);
        } catch (Exception e) {
            throw new ServiceException("Error converting Cloth to ClothDTO", e);
        }
    }

    @Override
    public Set<ClothDTO> getClothByUserIdAndSubcategory(long userId, String subcategory) {
        try {
            Set<Cloth> clothes = clothRepository.findByUserIdAndSubcategory(userId, subcategory);
            Set<ClothDTO> clothDTOs = ClothConverter.convertToClothDTOSet(clothes);

            // 添加图像字节到每个 ClothDTO
            for (ClothDTO clothDTO : clothDTOs) {
                String imageName = clothDTO.getImageName();
                if (imageName != null && !imageName.isEmpty()) {
                    byte[] imageBytes = imageService.getImageAsBytes(imageName);
                    clothDTO.setImageBytes(imageBytes);
                }
            }
            return clothDTOs;
        } catch (IOException e) {
            throw new ServiceException("Error retrieving image for Cloth", e);
        } catch (Exception e) {
            throw new ServiceException("Error converting Cloth to ClothDTO", e);
        }
    }


    @Override
    public ClothDTO getClothByUserIdAndUserClothId(long userId, int userClothId) {
        Cloth cloth = clothRepository.findByUserIdAndUserClothId(userId, userClothId);
        if (cloth == null) {
            throw new RuntimeException("Cloth not found for userId: " + userId + " and userClothId: " + userClothId);
        }
        try {
            ClothDTO clothDTO = ClothConverter.convertCloth(cloth);
            String imageName = clothDTO.getImageName(); // 假设 ClothDTO 中有 getImageName 方法
            if (imageName != null && !imageName.isEmpty()) {
                byte[] imageBytes = imageService.getImageAsBytes(imageName);
                clothDTO.setImageBytes(imageBytes); // 假设 ClothDTO 有 setImageBytes 方法
            }
            return clothDTO;
        } catch (IOException e) {
            throw new ServiceException("Error retrieving image for Cloth", e);
        } catch (Exception e) {
            throw new ServiceException("Error converting Cloth to ClothDTO", e);
        }
    }

    @Override
    public Long addClothByUserId(ClothDTO clothDTO, long userId) {
        int maxUserClothId = clothRepository.findMaxUserClothIdByUserId(userId);
        int newUserClothId = maxUserClothId + 1;

        clothDTO.setUserDTO(UserConverter.convertUser(userRepository.findById(userId).orElseThrow(() -> new RuntimeException("User not found for id: " + userId))));
        clothDTO.setUserClothId(newUserClothId);
        try {
            Cloth cloth = clothRepository.save(ClothConverter.convertCloth(clothDTO));
            return cloth.getId();
        } catch (Exception e) {
            throw new ServiceException("Error converting ClothDTO to Cloth", e);
        }
    }

    @Transactional
    @Override
    public void deleteClothByUserIdAndUserClothId(long userId, int userClothId) {
        clothRepository.deleteByUserIdAndUserClothId(userId, userClothId);
    }

    @Override
    public ClothDTO updateClothByUserIdAndUserClothId(long userId, int userClothId, String clothName, String imageName, String category, String subcategory) {
        Cloth clothInDB = clothRepository.findByUserIdAndUserClothId(userId, userClothId);
        if (StringUtils.hasLength(clothName) && !clothName.equals(clothInDB.getClothName())) {
            clothInDB.setClothName(clothName);
        }
        if (StringUtils.hasLength(imageName) && !imageName.equals(clothInDB.getImageName())) {
            clothInDB.setImageName(imageName);
        }
        if (StringUtils.hasLength(category) && !category.equals(clothInDB.getCategory())) {
            clothInDB.setCategory(category);
        }

        if (StringUtils.hasLength(subcategory) && !subcategory.equals(clothInDB.getSubcategory())) {
            clothInDB.setSubcategory(subcategory);
        }
        return ClothConverter.convertCloth(clothRepository.save(clothInDB));
    }
}
